﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace hw6
{
    public partial class Form1 : Form
    {
        private delegate void MyDelegate();
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }


        private void button1_Click(object sender, EventArgs e)
        {
            Task task_baidu = new Task(() => { Search_baidu("https://www.baidu.com/baidu?wd=" + textBox1.Text); });
            Task task_bing = new Task(() => { Search_bing("https://cn.bing.com/search?form=MOZTSB&pc=MOZI&q=" + textBox1.Text); });
            task_baidu.Start();
            task_bing.Start();
        }
        private void Search_baidu(string url)           // baidu
        {
            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;
            webClient.DownloadStringCompleted += Download1;
            webClient.DownloadStringAsync(new Uri(url));
            this.BeginInvoke(new MyDelegate(() => { textBoxBaidu.Text = "dling"; }) );   // 将转换后的数据填入textBox
        }
        private void Download1(object sender,DownloadStringCompletedEventArgs e)
        {
            this.BeginInvoke(new MyDelegate(() =>
            {
                textBoxBaidu.Text =e.Result.ToString();
            }));
        }


        private void Search_bing(string url)           // bing
        {
            WebClient webClient = new WebClient();
            byte[] recvdata
                = webClient.DownloadData(url);
            string response = Encoding.UTF8.GetString(recvdata);
            this.Invoke(new MyDelegate(() => { textBoxBing.Text = response.Substring(0, 100); }));
        }

        private string Parse(string html)
        {
            string str_ref = @"1[3589]\d{9}";
            MatchCollection matchs = new Regex(str_ref).Matches(html);
            str_ref = string.Empty;
            foreach (Match match in matchs)
            {
                str_ref += match.Value;
                str_ref += "\n";
            }
            return str_ref;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            WebClient webClient = new WebClient();
            byte[] recvdata
                = webClient.DownloadData(@"http://www.taohaoma.com/mobile/number");
            string response = Encoding.UTF8.GetString(recvdata);
            string str = Parse(response);
            textBoxBaidu.Text = str;
        }
    }
}
